package com.ecgsystem.thread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import com.ecgsystem.activity.OnlineECG;
import com.ecgsystem.constants.Constants;

import android.util.Log;

/**
 * Thread yeu cau lay tin hieu va nhan tin hieu realtime neu co
 * 
 * @author ANHTUAN. Created Sep 28, 2012.
 */
public class ThreadGetSignal extends Thread implements Constants {
	private InetAddress serverAddr;
	private DatagramSocket rec_socket;
	private DatagramSocket sen_socket;
	private boolean _run = false;
	private boolean firsttime = true;
	/**
	 * TODO Put here a description of this field.
	 */
	public static int ONLINE_STATUS;

	/**
	 * Contrutor mac dinh
	 * 
	 */
	public ThreadGetSignal() {
		this._run = true;
		this.firsttime = true;
	}

	@Override
	public void run() {
		final byte[] buf = new byte[700000];
		String type;
		try {
			this.serverAddr = InetAddress.getByName(UDP_SERVER_IP);
			this.sen_socket = new DatagramSocket();
			this.sen_socket.setSoTimeout(5000);

			String str_request = "RequestData|P0001";
			byte[] message = str_request.getBytes();
			DatagramPacket packet = new DatagramPacket(message,
					str_request.length(), this.serverAddr, MESS_SEND_PORT);
			this.sen_socket.send(packet);

			Log.d("sent", "da gui");

			packet = new DatagramPacket(buf, buf.length);
			while (this._run) {
				Log.d("Waitting ...", "d");
				this.sen_socket.receive(packet);
				// sen_socket.close();

				String mess = new String(buf, 0, packet.getLength());
				Log.d("nhan duoc", mess);

				StringTokenizer str = new StringTokenizer(mess, "|\t\n ");
				String sigStr;
				type = str.nextToken();

				if (packet.getLength() > 0) {
					if (type.equals("0")) {// Nhan ve thong tin dieu khien
						String status = str.nextToken();
						Log.d("mess", status);
						if (status.equals("Ready")) {
							ONLINE_STATUS = SERVER_READY;
							continue;
						} else if (status.equals("StopSend")) {
							ONLINE_STATUS = STOP_SEND;
							// OnlineECG.StopDraw();
							this._run = false;
						} else if (status.equals("NoWorkStation")) {
							Log.d("Thong bao", "No workstation");
							ONLINE_STATUS = NO_WORKSTATION;
							OnlineECG.StopDraw();
							this._run = false;
						}
					} else {// Nhan ve tin hieu do
						str.nextToken();
						if (this.firsttime) {
							for (int i = 0; i < 12; i++) {
								if (str.nextToken().equals("1")) {
									Constants.hasRecord[i] = true;
								} else {
									OnlineECG.QueueDraw[i] = null;
								}
							}
							this.firsttime = false;
						} else {
							for (int i = 0; i < 12; i++) {
								str.nextToken();
							}
						}
						try {
							while (str.hasMoreTokens()) {
								str.nextToken(); // bo qua thoi gian
								for (int i = 0; i < 12; i++) {
									sigStr = str.nextToken();
									if (Constants.hasRecord[i]) {
										Float signal = Float.valueOf(sigStr);
										OnlineECG.QueueDraw[i].add(signal);
									}
								}
								// Loi ben gui tin hieu
								// str.nextToken();
							}
						} catch (NoSuchElementException e) {
							e.printStackTrace();
							Log.d("Doc xong", "");
						} catch (NumberFormatException e) {
							e.printStackTrace();
							Log.d("Doc xong", "");
						}
						OnlineECG.startDraw = true;
					}
				} else {
					OnlineECG.StopDraw();
					this._run = false;
				}
			}

		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			this.sen_socket.close();
			Log.d("Socket", "Close socket");
			this._run = false;
			ONLINE_STATUS = CANNOT_CONNECT_SERVER;
		} catch (UnknownHostException e1) {
			ONLINE_STATUS = CANNOT_CONNECT_SERVER;
			// OnlineECG.StopDraw();
			this.sen_socket.close();
			e1.printStackTrace();
		} catch (SocketException e) {
			ONLINE_STATUS = CANNOT_CONNECT_SERVER;
			// OnlineECG.StopDraw();
			this.sen_socket.close();
			e.printStackTrace();
		} catch (IOException e) {
			ONLINE_STATUS = CANNOT_CONNECT_SERVER;
			// OnlineECG.StopDraw();
			this.sen_socket.close();
			e.printStackTrace();
		} catch (Exception e) {
			ONLINE_STATUS = CANNOT_CONNECT_SERVER;
			// OnlineECG.StopDraw();
			this.sen_socket.close();
			e.printStackTrace();
		}
	}

	/**
	 * TODO Put here a description of what this method does.
	 * 
	 */
	public void sendStop() {
		String str_request = "P0001|StopSend";
		byte[] message = str_request.getBytes();
		DatagramPacket packet = new DatagramPacket(message,
				str_request.length(), this.serverAddr, MESS_SEND_PORT);
		// this._run = false;
		try {
			this.sen_socket.send(packet);
		} catch (IOException exception) {
			// TODO Auto-generated catch-block stub.
			exception.printStackTrace();
		}
	}

	public void exit() {
		sen_socket.close();
		rec_socket.close();
	}
}
